#include "Stdafx.h"
#include "D3DXConstantTable.h"
#include "Direct3DDevice9.h"

#include <vcclr.h>

using namespace Vortex::Wrapper::Direct3D;

D3DXConstantTable::D3DXConstantTable(ID3DXConstantTable* handle) : _handle(handle) {
	_proxy = new D3DDeviceProxy(this);
}

D3DXConstantTable::~D3DXConstantTable() {
	_handle->Release();
	delete _proxy;
}

void D3DXConstantTable::SetDefaults() {
	_handle->SetDefaults(_proxy);
}

void D3DXConstantTable::SetDefaults(Direct3DDevice9^ device) {
	_handle->SetDefaults(device->NativeHandle);
}

LPVOID D3DXConstantTable::GetBufferPointer() {
	return _handle->GetBufferPointer();
}

DWORD D3DXConstantTable::GetBufferSize() {
	return _handle->GetBufferSize();
}

IntPtr D3DXConstantTable::FindConstantHandleByName(String^ constName) {
	char szConstName[256];
	{
		pin_ptr<const wchar_t> wszConstName = PtrToStringChars(constName);
		WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wszConstName, -1, szConstName, sizeof(szConstName), NULL, NULL);
	}

	D3DXHANDLE hConstant = _handle->GetConstantByName(NULL, szConstName);

	return IntPtr((void*)hConstant);
}

HResult D3DXConstantTable::SetConstantData(IntPtr constantHandle, void* pData, UINT bytesCount) {
	return HResult(_handle->SetValue(_proxy, (D3DXHANDLE)constantHandle.ToPointer(), pData, bytesCount));
}

HResult D3DXConstantTable::SetConstantData(Direct3DDevice9^ device, IntPtr constantHandle, void* pData, UINT bytesCount) {
	return HResult(_handle->SetValue(device->NativeHandle, (D3DXHANDLE)constantHandle.ToPointer(), pData, bytesCount));
}

void D3DXConstantTable::SetVertexShaderConstantF(UINT startRegister, const float* pData, UINT vector4fCount) {
	OnFloatConstantChange(startRegister, pData, vector4fCount);
}

void D3DXConstantTable::SetVertexShaderConstantI(UINT startRegister, const int* pData, UINT vector4iCount) {
	OnIntConstantChange(startRegister, pData, vector4iCount);
}

void D3DXConstantTable::SetVertexShaderConstantB(UINT startRegister, const BOOL* pData, UINT boolCount) {
	OnBoolConstantChange(startRegister, pData, boolCount);
}

void D3DXConstantTable::SetPixelShaderConstantF(UINT startRegister, const float* pData, UINT vector4fCount) {
	OnFloatConstantChange(startRegister, pData, vector4fCount);
}

void D3DXConstantTable::SetPixelShaderConstantI(UINT startRegister, const int* pData, UINT vector4iCount) {
	OnIntConstantChange(startRegister, pData, vector4iCount);
}

void D3DXConstantTable::SetPixelShaderConstantB(UINT startRegister, const BOOL* pData, UINT boolCount) {
	OnBoolConstantChange(startRegister, pData, boolCount);
}